package com.hlk.emos.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hlk.emos.wx.config.WxConfig;
import com.hlk.emos.wx.db.dao.UserDao;
import com.hlk.emos.wx.db.pojo.UserEntity;
import com.hlk.emos.wx.dto.RegisterDto;
import com.hlk.emos.wx.exception.EmosException;
import com.hlk.emos.wx.service.UserService;
import com.hlk.emos.wx.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;

/**
 * 用户表
 *
 * @author hlk hlk@gmail.com
 * @since v1.0.0 2021-05-19
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private WxConfig wxConfig;


    @Override
    public int registerUser(RegisterDto dto) {
        // 注册root用户
        if (dto.getRegisterCode().equals("000000")) {
            // 校验是否存在root用户
            LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserEntity::getRoot, 1);
            UserEntity userEntity = baseDao.selectOne(wrapper);
            if (Objects.isNull(userEntity)) {
                String openId = getOpenId(dto.getCode());
                UserEntity entity = new UserEntity();
                entity.setOpenId(openId)
                        .setNickname(dto.getNickname())
                        .setPhoto(dto.getPhoto())
                        .setStatus(1)
                        .setRole("[0]")
                        .setRoot(1)
                        .setCreateTime(new Date());
                baseDao.insert(entity);
                return entity.getId();
            } else {
                throw new EmosException("无法绑定超级管理员账号");
            }
        } else {

        }
        return 0;
    }

    @Override
    public Set<String> selectUserPermissions(int id) {
        return baseDao.selectUserPermissions(id);
    }

    @Override
    public int login(String code) {
        String openId = getOpenId(code);
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getOpenId, openId);
        UserEntity userEntity = baseDao.selectOne(wrapper);
        if (Objects.isNull(userEntity)) {
            throw new EmosException("用户不存在");
        }
        return userEntity.getId();
    }

    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", wxConfig.getAppId());
        map.put("secret", wxConfig.getAppSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }
}
